﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Media;

namespace Duellum.Wpf2d.Plugin
{
	public class ZSortedVisualCollection : ICollection<OverlayVisual>
	{
		VisualCollection innerColl;
		
		public ZSortedVisualCollection(Visual parent)
		{
			innerColl = new VisualCollection(parent);
		}
		
		public OverlayVisual this[int index] { get { return (OverlayVisual)innerColl[index]; } }

		public void Add(OverlayVisual item)
		{
			lock (innerColl.SyncRoot) {
				int position = FindPositionToInsert(item.ZOrder);
				
				if (position == -1)	innerColl.Add(item);
				else				innerColl.Insert(position, item);
			}
		}
		
		private int FindPositionToInsert(int zOrder)
		{
			for (int i=0; i<innerColl.Count; i++) {
				int lastZOrder = this[i].ZOrder;
				if (zOrder < lastZOrder) return i;
			}
			return -1;
		}

		public void Clear()
		{
			innerColl.Clear();
		}

		public bool Contains(OverlayVisual item)
		{
			return innerColl.Contains(item);
		}

		public void CopyTo(OverlayVisual[] array, int arrayIndex)
		{
			throw new NotSupportedException();
		}

		public int Count
		{
			get { return innerColl.Count; }
		}

		public bool IsReadOnly
		{
			get { return innerColl.IsReadOnly; }
		}

		public bool Remove(OverlayVisual item)
		{
			lock (innerColl.SyncRoot) {
				bool contains = innerColl.Contains(item);
				innerColl.Remove(item);
				return contains;
			}
		}
		
		public IEnumerator<OverlayVisual> GetEnumerator()
		{
			return innerColl.Cast<OverlayVisual>().GetEnumerator();
		}
		
		IEnumerator IEnumerable.GetEnumerator()
		{
			return innerColl.GetEnumerator();
		}
	}
}
